/** 
 * @func 格式化接口返回数据
 */
import { STATUS_CODE, SpanStatus } from '../common/constant'
import { options } from '../controllers/options'
export function resetHttpData(data) {

    const {
        elapsedTime,
        time,
        method = '',
        type,
        Status = 200,
        response,
        requestData } = data;

    let message = ''
    let status = ''
    if (Status == 0) {
        status = STATUS_CODE.ERROR
        message = elapsedTime <= options.overTime * 1000
            ? `请求失败，Status值为:${Status}`
            : '请求失败，接口超时';
    } else if (Status < 400) {
        status = STATUS_CODE.OK;
        if (options.handleHttpStatus && typeof options.handleHttpStatus == 'function') {
            if (options.handleHttpStatus(data)) {
                status = STATUS_CODE.OK;
            } else {
                status = STATUS_CODE.ERROR;
                message = `接口报错，报错信息为：${typeof response == 'object' ? JSON.stringify(response) : response
                    }`;
            }
        }
    } else {
        status = STATUS_CODE.ERROR
        message = `请求失败，Status值为:${Status}，${fromHttpStatus(Status)}`;
    }
    message = `${data.url}; ${message}`;
    return {
        url: data.url,
        time,
        status,
        elapsedTime,
        message,
        requestData: {
            httpType: type,
            method,
            data: requestData || '',
        },
        response: {
            Status,
            data: status == STATUS_CODE.ERROR ? response : null,
        },
    };
}

function fromHttpStatus(httpStatus) {
    if (httpStatus < 400) {
        return SpanStatus.Ok;
    }
    if (httpStatus >= 400 && httpStatus < 500) {
        switch (httpStatus) {
            case 401:
                return SpanStatus.Unauthenticated;
            case 403:
                return SpanStatus.PermissionDenied;
            case 404:
                return SpanStatus.NotFound;
            case 409:
                return SpanStatus.AlreadyExists;
            case 413:
                return SpanStatus.FailedPrecondition;
            case 429:
                return SpanStatus.ResourceExhausted;
            default:
                return SpanStatus.InvalidArgument;
        }
    }
    if (httpStatus >= 500 && httpStatus < 600) {
        switch (httpStatus) {
            case 501:
                return SpanStatus.Unimplemented;
            case 503:
                return SpanStatus.Unavailable;
            case 504:
                return SpanStatus.DeadlineExceeded;
            default:
                return SpanStatus.InternalError;
        }
    }
    return SpanStatus.UnknownError;
}
